<?php
defined('IN_MAIN') or exit('Invalid Access!');

function calc_pool($in_date){
/*
This function calculates the CTO pool for all the members that qualify for these pools. 3 pools are calculated, each with 1% of total company
sales, total 3%.

1st pool: 1%
member must have group sales volume >= 200,000, with minimum 2 legs having >= 50,000

2nd pool: 1%
member must have group sales volume >= 500,000, with minimum 3 legs having >= 100,000. Member who qualifies for 2nd pool also qualify 1st pool.

3rd pool: 1%
member must have group sales volume >= 1,000,000, with minimum 5 legs having >= 100,000. Member who qualifies for 2nd pool also qualify 1st & 2nd pool.

pool is shared equally among qualifiers. If no qualifiers, the particular pool amount will be carry forward to next month.
*/

	//globalize access to pool, min_maintain
	global $vars;
	$db=$vars["db"];
	$pairing_volume_type = $vars['pairing_volume_type'];
	$pool = $vars['pool'];
	$min_maintain = $vars['min_maintain'];
	
	//calc_date = get the start and end of the input in_date
	$year=date("Y", strtotime($in_date));
	$month=date("n", strtotime($in_date));
	$calc_date['start']=date('Y-m-d H:i:s', mktime(0, 0, 0, $month, 1, $year));
	$calc_date['end']=date('Y-m-d H:i:s', mktime(23, 59, 59, $month+1, 0, $year));
	$last_month_time = mktime(0, 0, 0, $month-1, 1, $year);
	$last_year=date("Y", $last_month_time);
	$last_month=date("n", $last_month_time);
	//total_pool = count(pool) //number of pool
	$total_pool = count($pool);
	
	//xxx members = get all the members that have personal maintain / purchases of more than min_maintain (200)
	//members = get all the members that is activated
	$t=@mysql_num_rows($r=mysql_query("select * from $db->users where activated='y'"));
	//foreach members
	for($i=0;$i<$t;$i++){
		$member = mysql_fetch_assoc($r);
		//uid = this member[id]
		//personal_volume = get all the purchases by this member
		$uid = $member['id'];
		$personal_volume = $member['personal_volume'];
		//member_legs = get this member all legs
		$member_legs = get_member_matrix_leg($uid, $pairing_volume_type, $calc_date['start'], $calc_date['end']);
		/*lc_date['end']);
		/*
			member_legs will then looks like this:
			member_legs[index][id]
			member_legs[index][position]
			member_legs[index][volume] - volume should include this day volume (1st sale of a member only) plus any carry forward from previous day if applicable
			member_legs[index][avolume] - avolume should include only this day volume (1st sale of a member only), without any carry forward
			member_legs[index][volume_type][unit]
				[volume_type] is the type of purchase (in BV), can be 400, 1200, 2800, 6000, 800, 2400, 5600, 1600, 4800, or 3200, 
				[unit] means how many of this type of purchase has occur within this leg for this day (1st sale of a member only) plus any carry forward from previous day if applicable
			member_legs[index][volume_type][left_unit] - same with unit
			member_legs[index][volume_type][aunit] - aunit should include only this day unit (1st sale of a member only), without any carry forward
			
			position is the matrix position, sort by largest volume (include carry forward) leg 1st (accumulated total of all volume as biggest)
		*/
		
		//group_volume = personal_volume + all avolume from member_legs
		$group_volume = $personal_volume;
		if(count($member_legs)){
			foreach($member_legs as $detail){
				$group_volume += $detail['avolume'];
			}
		}
		//for j = total_pool to minimum of pool (1): highest to lowest: pool-loop
		for ($j=$total_pool;$j>0;$j--){
			//if group_volume >= pool[j][volume]
			if ($group_volume >= $pool[$j]['volume']){
				//min_leg = pool[j][min_leg]
				$min_leg = $pool[$j]['min_leg'];
				//foreach member_legs as position => details
				if(count($member_legs)){
					foreach ($member_legs as $details){
						//if min_leg > 0
						if ($min_leg > 0){
							//if details[avolume] >= pool[j][min_leg_volume]
							if ($details['avolume'] >= $pool[$j]['min_leg_volume']){
								//min_leg -= 1
								$min_leg -= 1;
							}
						}
					}
				}
				//if min_leg = 0 //achieve this pool
				if ($min_leg == 0){
					//achieve for lower rank pool too
					//for k = j to 1
					for ($k=$j;$k>=1;$k--){
						//pool_qualifier[k][] = uid
						//pool_share[k] += 1
						$pool_qualifier[$k][] = $uid;
						$pool_share[$k] += 1;
					}
					//exit pool-loop
					$j=0;
				}
			}
		}
	}
	
	//cto = get all the purchase volumes (1st sale of member only) for the input in_date for confirmed purchases
	$cto = @mysql_result(mysql_query("select sum(total_bv) from $db->purchase where first_sale='y' and status='confirmed' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'"), 0) or 0;
	//for i = 1 to total_pool
	for ($i=1;$i<=$total_pool;$i++){
		//poolbf = get any brought forward of this pool for previous month
		$poolbf = @mysql_result(mysql_query("select amount from $db->pool_cf where type='$i' and month='$last_month' and year='$last_year'"), 0) or 0;
		//pool_amount = (pool[i][percent] * cto / 100) + poolbf
		$pool_amount = round($cto * $pool[$i]['percent'] / 100, 2) + $poolbf;
		//if count(pool_qualifier[i])
		if (count($pool_qualifier[$i])){
			//comm_amount = pool_amount / pool_share[i]
			$comm_amount = round($pool_amount / $pool_share[$i], 2);
			//foreach pool_qualifier[i]
			for($j=0,$t2=count($pool_qualifier[$i]);$j<$t2;$j++){
				//uid = pool_qualifier[i][index]
				$uid = $pool_qualifier[$i][$j];
				//insert the commission into the member_comm table with type = pool-i, uid = uid, amount = comm_amount, percent = pool[i][percent], year, month, datetime
				$sql = "insert into $db->member_comm (uid, type, amount, percent, year, month, status, cdate) values ('$uid', '$i', '$comm_amount', '".$pool[$i]['percent']."', '$year', '$month', 'confirmed', '".ndate($vars['system_date_format'])."')";
				//if insert fail record the error in the variable insert_pooli_error
				$insert_comm_detail="UID: $uid Amount: $comm_amount Percent: ".$pool[$i]['percent']."%<br />\n";
				if(!mysql_query($sql)){
					$insert_error[$i].=$insert_comm_detail."SQL: $sql<br />\n";
				}else{
					$insert_success[$i].=$insert_comm_detail;
				}
				//member_comm[uid] += comm_amount
				$member_comm[$uid] += $comm_amount;
			}
		}else{
			//insert into the pool_cf table with type = pool-i, amount = pool_amount, year, month
			$sql = "insert into $db->pool_cf (type, amount, year, month) values ('$i', '$pool_amount', '$year', '$month')";
			//if insert error record the error in the variable insert_poolcf_error
			if(!mysql_query($sql)){
				$insert_poolcf_error.="Pool $i: Amount: $pool_amount Percent: ".$pool[$i]['percent']."%<br />\n";
			}
		}
	}
	
	//if exist(insert_pool1_error or insert_pool2_error or insert_pool3_error or insert_poolcf_error or update_ewallet_error or ewallet_trans_error)
	if($insert_error || $insert_poolcf_error){
		$insert_errmsg.=($insert_error[1]? "Failed Pool 1 Calculations:<br />\n<br />\n$insert_error[1]" : "").
		($insert_error[2]? "Failed Pool 2 Calculations:<br />\n<br />\n$insert_error[2]" : "").
		($insert_error[3]? "Failed Pool 3 Calculations:<br />\n<br />\n$insert_error[3]" : "").
		($insert_poolcf_error? "Failed Pool Carry Forward Calculations:<br />\n<br />\n$insert_poolcf_error" : "");
		$result["errmsg"] .= $insert_errmsg;
	}else{
		$result["status"] = true;
	}
	
	return $result;
}
?>